package com.kx.center.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.kx.center.entity.ErrorLog;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.service.ErrorLogService;
import com.kx.center.util.IPUtil;

public class CustomHandlerExceptionResolver implements HandlerExceptionResolver {

	@Autowired
	ErrorLogService logService;

	@SuppressWarnings("unchecked")
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object arg2,
			Exception ex) {
		ModelAndView mav = new ModelAndView();
		String viewName = ClassUtils.getShortName(ex.getClass());
		ErrorLog errorLog = new ErrorLog();
		
		errorLog.setErrorType(viewName);	
		errorLog.setErrorInfo(ex.getMessage() + ex.getStackTrace());
		errorLog.setRequestUri(request.getRequestURI());
		errorLog.setRequestIP(IPUtil.getIp(request));
		MappingJackson2JsonView view  = new MappingJackson2JsonView();
		switch (viewName) {
		case "IllegalTokenException":
			// token不合法 记录日志 返回前端
			errorLog.setErrorLevel(2);
			logService.addLog(errorLog);
			
			@SuppressWarnings("rawtypes")
			Map map = new HashMap();
			map.put("msg", "token不合法");
			map.put("code",MessageCode.ILLEGAL_TOKEN.getValue());
			
			view.setAttributesMap(map);
			mav.setView(view);
			return mav;
			
		case "InvalidationTokenException":
			errorLog.setErrorLevel(2);
			logService.addLog(errorLog);
			@SuppressWarnings("rawtypes")
			Map map2 = new HashMap();
			map2.put("msg", "token失效");
			map2.put("code",MessageCode.INVALIDATION_TOKEN.getValue());
			view.setAttributesMap(map2);
			mav.setView(view);
			return mav;
			
		case "EmptyTokenException":
			errorLog.setErrorLevel(2);
			logService.addLog(errorLog);
			@SuppressWarnings("rawtypes")
			Map map3 = new HashMap();
			map3.put("msg", "token为空");
			map3.put("code",MessageCode.EMPTY_TOKEN.getValue());
			
			view.setAttributesMap(map3);
			mav.setView(view);
			return mav;
			

		default:
			errorLog.setErrorLevel(1);
			logService.addLog(errorLog);
			@SuppressWarnings("rawtypes")
			Map map4 = new HashMap();
			map4.put("msg", "服务器异常");
			map4.put("code",MessageCode.SERVER_ERROR.getValue());
			
			view.setAttributesMap(map4);
			mav.setView(view);
			return mav;
		}
		
	}

}
